package com.piece.core.pay.client.impl.alipay;

import com.alipay.api.AlipayApiException;
import com.alipay.api.domain.AlipayTradePrecreateModel;
import com.alipay.api.request.AlipayTradePrecreateRequest;
import com.alipay.api.response.AlipayTradePrecreateResponse;
import com.piece.core.framework.support.response.AjaxResponse;
import com.piece.core.framework.util.string.StringUtil;
import com.piece.core.pay.dto.PayOrderUnifiedReqDTO;
import com.piece.core.pay.enums.PayChannelType;
import lombok.extern.slf4j.Slf4j;

/**
 * 支付宝扫码支付实现类
 * <p>参考: https://opendocs.alipay.com/open/repo-0038t7?ref=api</p>
 */
@Slf4j
public class AliPayQrPayClient extends AbstractAliPayClient {

    public AliPayQrPayClient(String channelId, AliPayClientConfig config) {
        super(channelId, PayChannelType.ALIPAY_QR.getCode(), config, new AliPayResponseMapping());
    }

    @Override
    public AjaxResponse doUnifiedOrder(PayOrderUnifiedReqDTO reqDTO) {
        AlipayTradePrecreateModel model = new AlipayTradePrecreateModel();
        model.setOutTradeNo(reqDTO.getMerchantOrderId());
        model.setSubject(reqDTO.getSubject());
        model.setBody(reqDTO.getBody());
        model.setTotalAmount(calculateAmount(reqDTO.getAmount()).toString());

        AlipayTradePrecreateRequest request = new AlipayTradePrecreateRequest();
        request.setBizModel(model);
        request.setNotifyUrl(StringUtil.isNotEmpty(config.getNotifyUrl()) ? config.getNotifyUrl() : reqDTO.getNotifyUrl());
        request.setReturnUrl(StringUtil.isNotEmpty(config.getReturnUrl()) ? config.getReturnUrl() : reqDTO.getReturnUrl());
        // 执行请求
        AlipayTradePrecreateResponse response;
        try {
            response = client.execute(request);
        } catch (AlipayApiException e) {
            log.error("[支付宝扫码支付发起支付失败]：{}", e);
            return AjaxResponse.error("支付宝扫码支付发起支付失败");
        }

        return AjaxResponse.result(codeMapping.apply(response.getCode(), response.getMsg()), response);
    }
}
